;(function (win, $) {

    // 首页
    app.namespace('app.model.home')

    $.extend(app.model.home, {
        init: function () {
            this.setBanner()
            this.bind()
            this.navAnim()
        },
        setBanner: function () {
            var homeBanner = $('#homeBanner'),
                homeBannerNum = $('#homeBannerNum'),
                len = $('.swipe-wrap').find('.swipe-items').length,
                str = '<a></a>',
                end = ''

            for (var i = 0; i < len; i++) {
                if (!i) {
                    end = '<a class="active"></a>'
                } else {
                    end += str
                }
            }

            homeBannerNum.append(end)

            this.setSwipe(homeBanner, {
                leftBtn: $('#swipeLeft'),
                rightBtn: $('#swipeRight'),
                callback: function (index, elem) {
                    var link = $('#homeBannerNum a')
                    link.removeClass('active')
                    link.eq(index).addClass('active')
                }
            })
        },
        navAnim: function () {
            var w = 0
            $('.category-list li').hover(function () {
                $(this).find('a').stop().animate({left: 0})
            }, function () {
                w = $(this).width() - 15
                $(this).find('a').stop().animate({left: '-' + w})
            })

            $('.contact-list li').hover(function () {
                $(this).find('span').stop().animate({top: 0})
            }, function () {
                $(this).find('span').stop().animate({top: '+58'})
            }).on('click', function () {
                location.href = $(this).find('a')[0].href
            })
        },
        setSwipe: function (obj, options) {
            var opts = $.extend({}, {
                    auto: 3000,
                    disableScroll: true,
                    leftBtn: '',
                    rightBtn: ''
                }, options),
                leftBtn = opts.leftBtn,
                rightBtn = opts.rightBtn,
                slide = null

            if (obj.length > 0) {
                slide = obj.Swipe(opts).data('Swipe')
            }

            if (slide && opts.leftBtn.length > 0 && opts.rightBtn.length > 0) {
                opts.leftBtn.on('click', slide.prev)
                opts.rightBtn.on('click', slide.next)
            }
        },
        // 绑定事件
        bind: function () {
            var self = this
        },
    })

}(window, jQuery))

;(function (win, $) {

    // 博客
    app.namespace('app.model.blog')

    $.extend(app.model.blog, {
        el: {
            shareAction: $('#js-blog-action .js-share-action'),
            likeBtn: $('#js-like-btn'),
            popup: null,
        },
        data: {
            blogStoreKey: 'milu.blog.likes.ids',
            likedIds: [],
        },
        init: function () {
            this.created()
            this.bind()
            this.bindShareNav()
            this.initQrCode()
            this.initClipboard()
            this.initLike()
        },
        initClipboard() {
            typeof ClipboardJS !== 'undefined' && (this.clipboard = new ClipboardJS($('.link')[0]))
        },
        created() {
            this.data.likedIds = JSON.parse(localStorage.getItem(this.data.blogStoreKey) || '[]');
        },
        initLike: function () {
            var id = this.el.likeBtn.data('id')

            if (this.data.likedIds.includes(id)) {
                this.el.likeBtn.addClass('ok')
            }
        },
        initQrCode: function () {
            $(".wechat-qrcode-img").qrcode({
                width: 140,
                height: 140,
                render: "canvas",
                typeNumber: -1,
                correctLevel: 0,
                background: "#ffffff",
                foreground: "#000000",
                text: location.href
            })
        },
        // 绑定事件
        bind: function () {
            var self = this

            // 点赞评论
            $('#js-blog-action .js-post-btn').on('click', function (e) {
                var currentTarget = $(e.currentTarget),
                    type = currentTarget.data('type')

                if (type && currentTarget) {
                    var badge = currentTarget.attr('badge')
                    self[`handle${app.capitalize(type)}`](currentTarget, badge)
                }

                e.stopPropagation()
                return false
            })

            // 分享
            $('.share-item', this.el.shareAction).off('click.share').on('click.share', function (e) {
                var currentTarget = e.currentTarget,
                    type = $(currentTarget).data('type'),
                    ss = ['qq', 'weibo']

                if (ss.includes(type)) {
                    var options = {
                        type,
                        url: location.href,
                        title: document.title,
                        pics: '',
                        summary: '摘要',
                        desc: '描述',
                        appkey: 'abcdef',
                    }
                    app.shareTo(options)
                } else {
                    self.initCopy(currentTarget)
                }

                e.stopPropagation()
                return false
            })
        },
        // 复制文章链接
        initCopy: function (el) {
            var clipboard = this.clipboard

            el.setAttribute("data-clipboard-text", location.href)

            clipboard.on('success', function (e) {
                e.clearSelection()
                return app.ui.toast('链接已复制')
            })
        },
        // 分享
        bindShareNav: function () {
            var popup = this.el.shareAction.find('.action-share-popup')

            this.el.shareAction.mouseenter(function () {
                popup.stop(true).fadeIn()
            }).mouseleave(function () {
                popup.stop(true).fadeOut()
            })
        },
        // 是否点赞
        liked(id) {
            return this.data.likedIds.includes(id);
        },
        // 点赞
        handleLike: function (el, badge) {
            var self = this,
                id = el.data('id')

            if (el.hasClass('ok') || this.liked(id)) {
                app.ui.toast('感谢支持，您已赞过~！')
                return
            }

            var url = `/article/${id}/likes`,
                data = { likes: ++badge }

            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data,
                success: function (res) {
                    if (!res.code) {
                        self.handleLikeOk(el, res?.data)
                    } else {
                        app.ui.toast(res.msg)
                    }
                },
                error: function (res) {
                    app.ui.toast(res.msg)
                }
            })
        },
        // 处理点赞成功
        handleLikeOk: function (el, data) {
            el.addClass('ok').attr('badge', data)

            this.data.likedIds = [...this.data.likedIds, el.data('id')]
            localStorage.setItem(this.data.blogStoreKey, JSON.stringify(this.data.likedIds))
        },
        // 评论跳转
        handleComment: function (el, badge) {
            var author = $('#author')

            $('html, body').animate({ scrollTop: author.offset().top }, 500, 'linear', function () {
                author.focus()
            })
        },
        handleShare: function () {
            alert('commnet')
        },
    })

}(window, jQuery))

;(function (win, $) {
    // 留言
    app.namespace('app.model.message')

    $.extend(app.model.message, {
        init: function () {
            this.bind()
            this.sendComment()
            this.sendMsg()
            this.saySupport()
            // this.setImgWidth()
        },
        bind: function () {
            var self = this

            // 图片验证码
            $('#verifyImg').on('click', function () {
                var scope = this
                var url = '/verify?random=' + Date.now()
                    $.ajax({
                        url: url,
                        success: function (res) {
                            if (!res.code) {
                                $('#captchaId').val(res.data.captchaId)
                                scope.src = res.data.captchaImg
                            }
                        }
                    })
            }).trigger('click')

            $('#email').on('blur', function () {
                self.loadGravatar(this)
            })

            // 微信显示和隐藏
            var weixin = $('.weixin')
            var wxGo = weixin.find('.img')
            weixin.hover(function (){
                wxGo.fadeIn()
            }, function (){
                wxGo.fadeOut()
            })
        },
        getFormFileds: function () {
            var inputs = $('form').serializeArray()
            var data = {}
            $.each(inputs, function (i, v) {
                data[v.name] = v.name === 'bid' ? +v.value : v.value
            })

            return data
        },
        // 提交评论
        sendComment: function () {
            this.save({ btn: $('#sendComment'), url: '/comment/add' })
        },
        // 提交留言
        sendMsg: function () {
            this.save({ btn: $('#sendMsg'), url: '/message/add' })
        },
        save: function ({ form = $('#form1'), btn, url }) {
            var self = this,
                msg = null,
                fields = [
                    { el: '#author', label: '昵称' },
                    { el: '#email', label: '邮箱' },
                    { el: '#content', label: '评论内容' },
                    { el: '#verify', label: '验证码' },
                ]

            btn.on('click', function (e) {

                if (self.checkMsg(fields)) {
                    msg = $('<div/>').appendTo('.blog-tips-info').addClass('comment-msg')

                    var data = JSON.stringify(self.getFormFileds())

                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data,
                        contentType: 'application/json',
                        success: function (res) {
                            if (!res.code) {
                                var data = res.data
                                res.msg = '提交成功'
                                msg.html(res.msg)

                                form[0].reset()
                                $('#author').focus()

                                var avatar = `https://v1.alapi.cn/api/avatar?email=${data.email}&size=100`
                                var str = '<div class="comment-headimg"><a href="' + data.url + '" title="' + data.username + '" target="_blank"><img width="44" height="44" alt="' + data.username + '" src="' + avatar + '"></a></div>'
                                    + '<div class="comment-main">'
                                    + '<div class="comment-name clearfix">'
                                    + '<div class="comment-user">'
                                    + '<h1>' + data.username + '</h1>'
                                    + '</div>'
                                    + '<div class="comment-revert"><time class="comment-date">' + self.curentTime() + '</time></div>'
                                    + '</div>'
                                    + '<div class="comment-content">' + data.content + '</div>'
                                    + '</div>'

                                $('<li>' + str + '</li>').prependTo('.comment-list').css({opacity: 0}).fadeTo(800, 1)
                            } else {
                                msg.html(res.msg)
                            }

                            setTimeout(function () {
                                msg.fadeOut(800).remove()
                            }, 1200)
                        },
                        error: function (res) {
                            msg.html(res.msg)
                        }
                    })
                }

                e.preventDefault()
                return false
            })
        },
        curentTime: function () {
            var now = new Date(),
                year = now.getFullYear(),      //年
                month = now.getMonth() + 1,    //月
                day = now.getDate(),           //日

                hh = now.getHours(),            //时
                mm = now.getMinutes(),          //分
                s = now.getSeconds(),          //分

                clock = year + '-'

            if (month < 10)
                clock += '0'

            clock += month + '-'

            if (day < 10)
                clock += '0'

            clock += day + ' '

            if (hh < 10)
                clock += '0'

            clock += hh + ':'
            if (mm < 10) clock += '0'
            clock += mm
            clock += s

            return clock
        },
        loadGravatar: function (obj) {
            var src = obj.value,
                size = 100,
                m_url = ''

            if (src.indexOf('@') < 0) return false

            m_url = `https://v1.alapi.cn/api/avatar?email=${src}&size=${size}`

            $('#gravatarView').attr('src', m_url)
            $('#gravatarInput').val(m_url)
        },
        setImgWidth: function () {
            var w_width = $(window).width(),
                list = $('.wroks-list li')

            if (w_width > 1360) {
                list.css({marginRight: parseInt((w_width - 130 - 4 * list.outerWidth(true)) / 3)})
                list.each(function (i, n) {
                    if ((i + 1) % 4 === 0) {
                        $(this).css({marginRight: 0})
                    }
                })
            }

        },
        checkMsg: function (fileds) {
            return fileds.every(v => this.checkHandler($(v.el), v.label))
            // return this.checkHandler($('#author'), '昵称') && this.checkHandler($('#email'), '邮箱') && this.checkHandler($('#content'), '评论内容') && this.checkHandler($('#verify'), '验证码')
        },
        checkHandler: function (el, msg) {
            if (el.length > 0 && el.val().length < 1) {
                app.toast('请输入您的' + msg + '！')
                el.focus()
                return false
            }
            return true
        },
        saySupport: function () {
            var userId = 0

            $('.blog-ok,.info-sayok').on('click', function () {
                var that = this
                userId = $(this).data('userid')

                var yetId = app.cookie.getCookie('userid'),
                    yetArr = '',
                    isYet = false

                if (yetId) { // 已评论过其它
                    yetArr = yetId.split('|')

                    for (var i = 0, len = yetArr.length; i < len; i++) {
                        if (userId == yetArr[i]) {
                            isYet = true
                        }
                    }

                    if (isYet) {
                        alert('谢谢支持,您已赞过~！')
                    } else {
                        app.cookie.set('userid', yetId + '|' + userId, 1)
                    }
                } else {
                    app.cookie.set('userid', userId, 1)
                }

                if ($(this).hasClass('blog-yetok') || $(this).hasClass('blog-yetok')) {
                    return
                }

                $.ajax({
                    url: URL + '/support',
                    type: 'get',
                    dataType: 'json',
                    data: 'id=' + userId,
                    success: function (msg) {
                        var ok = null
                        if (msg.data === 1) {
                            $(that).addClass('blog-yetok')

                            if (that.className.indexOf('info-sayok') >= 0) {
                                $(that).html($(that).html() - 0 + 1)
                            } else {
                                ok = $(that).find('.blog-oknum')
                                ok.html(ok.html() - 0 + 1)
                            }
                        } else {
                            alert(msg.info)
                        }
                    },
                    error: function (msg) {
                        alert(msg.info)
                    }
                })

            })
        }
    })

}(window, jQuery))

$(function () {
    app.model.home.init()
    app.model.blog.init()
    app.model.message.init()
})